package com.hxl.tech.gateway.auth.service;


import com.hxl.tech.gateway.auth.context.ContextHolder;
import com.hxl.tech.gateway.auth.dao.OpenApiApprovalDao;
import com.hxl.tech.gateway.auth.dto.UserInfo;
import com.hxl.tech.gateway.auth.model.OpenApiApproval;
import com.hxl.tech.gateway.common.constant.AppConstant;
import com.hxl.tech.gateway.common.util.RedisUtil;
import edu.emory.mathcs.backport.java.util.Arrays;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import javax.persistence.EntityManager;
import javax.transaction.Transactional;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 开放接口授权 Service
 * @author soliddq
 * @date 2023-10-10
 */
@Service
@RequiredArgsConstructor
@Transactional
public class OpenApiApprovalService {

    private final EntityManager entityManager;
    private final OpenApiApprovalDao openApiApprovalDao;

    public OpenApiApproval read(OpenApiApproval.Id id) {

        return entityManager.find(OpenApiApproval.class, id);
    }

    public List<OpenApiApproval> find(String appId) {

        return openApiApprovalDao.find(appId);
    }

    public void save(OpenApiApproval openApiApproval) {

        OpenApiApproval origOpenApiApproval = this.read(openApiApproval.getId());
        if (Objects.isNull(origOpenApiApproval)) {
            UserInfo userInfo = ContextHolder.getUserInfo();
            openApiApproval.setCreateBy(userInfo.getRealName());
            openApiApproval.setCreateTime(LocalDateTime.now());
            entityManager.persist(openApiApproval);

            String appKey = AppConstant.REDIS_API_APPROVAL_PREFIX + openApiApproval.getId().getAppId();
            List<String> apis = Objects.nonNull(RedisUtil.get(appKey)) ? Arrays.asList(RedisUtil.get(appKey).toString().split(",")) : new ArrayList<>(0);
            apis.add(openApiApproval.getId().getApiName());
            RedisUtil.set(appKey, String.join(",", apis), 0, TimeUnit.MINUTES);
        }
    }

    public void delete(OpenApiApproval.Id id) {

        OpenApiApproval origOpenApiApproval = this.read(id);
        if (Objects.nonNull(origOpenApiApproval)) {
            entityManager.remove(origOpenApiApproval);

            String appKey = AppConstant.REDIS_API_APPROVAL_PREFIX + id.getAppId();
            List<String> apis = Objects.nonNull(RedisUtil.get(appKey)) ? Arrays.asList(RedisUtil.get(appKey).toString().split(",")) : new ArrayList<>(0);
            apis.remove(id.getApiName());
            RedisUtil.set(appKey, String.join(",", apis), 0, TimeUnit.MINUTES);
        }
    }
}
